// pages/order/goodsSure/goodsSure.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		buyType: 0,
		couponShow: false,
		goodsId: 0,
		goodsSKUId: 0,
		chooseSKU: null,
		goodsNum: 0,
		cartIds: '',

		// 订单数据
		address: null,
		coupon_list: [],
		delivery: "10",
		deliverySetting: ["10", "20"],
		exist_address: false,
		express_price: "0.00",
		extract_shop: [],
		goods_list: [],
		intra_region: true,
		order_pay_price: "0.00",
		order_total_num: "1",
		order_total_price: "0.00",
		goods_total_price: "0.00",
		point_total_price: "0.00",
		coupon_total_price: "0.00",
		user_points: "0",
		pay_type: 20,
		points_setting: null,
		point: {
			subtract_goodsTotalPrice: "0.00",
			usage_quantity: "0"
		},
		remark: '',

		// 是否开启积分兑换
		is_point_exchange: 0,
		// 是否选择优惠券
		chooseCoupon: null,
		// 门店列表
		shopList: [],
		chooseShop: null,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		if (options.goods_id) {
			this.data.goodsId = options.goods_id;
			this.data.goodsSKUId = parseInt(options.goods_sku_id);
			this.data.goodsNum = options.goods_num;
			this.loadGoodsDetail();
		} else {
			this.data.cartIds = decodeURIComponent(options.cart_ids);
			this.loadCartList();
		}

		wx.emitter.on('address.choose', this.chooseAddress);
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function(options) {
		wx.emitter.off('address.choose', this.chooseAddress)
	},

	// 用户选择地址
	chooseAddress: function(res) {
		this.setData({
			address: res
		});
	},

	// 选择优惠券
	chooseCouponChange: function(e) {
		this.groupSetData(() => {
			const chooseCoupon = e.detail;
			this.data.is_point_exchange = 0;
			this.setData({
				chooseCoupon: chooseCoupon,
				is_point_exchange: 0
			});
			this.updateTotalAmount();
		});
	},

	// 加载商品详情
	loadGoodsDetail: function() {
		return wx.http.get('api/order/buyNow', {
			goods_id: this.data.goodsId,
			goods_sku_id: this.data.goodsSKUId,
			goods_num: this.data.goodsNum,
			delivery: 10,
			shop_id: 0,
			point: 1,
		}).then((res) => {
			this.groupSetData(() => {
				const data = res.data.data;
				data.point_max_amout = wx.BigNumber(data.order_pay_price)
					.times(data.points_setting.discount.max_money_ratio)
					.div(100)
					.toFixed(2, wx.BigNumber.ROUND_DOWN);
				this.setData(data);

				this.updateTotalAmount();
			});
			return res.data.data;
		}, (err) => {
			console.warn("api/goods/detail", err)
		});
	},

	// 加载选中的购物车商品
	loadCartList: function() {
		return wx.http.get('api/order/cart', {
			cart_ids: this.data.cartIds,
			point: 1
		}).then((res) => {
			this.groupSetData(() => {
				res.data.data.buyType = 1;

				const data = res.data.data;
				data.point_max_amout = wx.BigNumber(data.order_pay_price)
					.times(data.points_setting.discount.max_money_ratio)
					.div(100)
					.toFixed(2, wx.BigNumber.ROUND_DOWN);
				this.setData(data);

				this.updateTotalAmount();
			});
			return res.data.data;
		}, (err) => {
			console.warn("api/order/cart", err)
		});
	},

	// 保存用户留言
	remarkInput: function(e) {
		this.data.remark = e.detail.value;
	},

	// 修改商品数量
	modifyGoodsNumTap: function(e) {
		const dataset = e.currentTarget.dataset,
			index = dataset.index,
			type = dataset.type;

		const item = this.data.goods_list[index];
		let totalNum = item.total_num;

		// 减少
		if (type === '0') {
			totalNum = totalNum > 1 ? totalNum - 1 : 1;
		} else { // 增加
			totalNum++;
		}

		this.groupSetData(() => {
			const totalNumKey = `goods_list[${index}].total_num`;
			const totalPriceKey = `goods_list[${index}].total_price`;
			const totalPrice = new wx.BigNumber(item.goods_price).multipliedBy(totalNum).toFixed(2, wx.BigNumber.ROUND_DOWN);
			this.setData({
				[totalNumKey]: totalNum,
				[totalPriceKey]: totalPrice,
			});

			this.updateTotalAmount();

			// 更新coupon
			this.updateCoupon(totalNum);
		});
	},

	// 重新计算总价格
	updateTotalAmount: function() {
		// 商品金额
		let goodsTotalPrice = new wx.BigNumber('0.00');
		this.data.goods_list.forEach(it => {
			goodsTotalPrice = goodsTotalPrice.plus(it.total_price)
		});

		// 订单总金额
		let orderTotalPrice = goodsTotalPrice.plus('0.00');
		if (parseInt(this.data.delivery) === 10) {
			orderTotalPrice = orderTotalPrice.plus(this.data.express_price);
		}

		// 优惠券折扣金额
		let couponTotalPrice = new wx.BigNumber('0.00');
		let chooseCoupon = this.data.chooseCoupon;
		if (chooseCoupon) {
			// 如果是折扣券
			if (chooseCoupon.coupon_type.value === 20) {
				couponTotalPrice = new wx.BigNumber(10);
				couponTotalPrice = couponTotalPrice.minus(chooseCoupon.discount).div(10).multipliedBy(orderTotalPrice);
			} else {
				couponTotalPrice = new wx.BigNumber(chooseCoupon.reduce_price);
			}
		}

		// 积分折扣金额
		let pointTotalPrice = new wx.BigNumber('0.00');
		if (this.data.is_point_exchange) {
			// const pointSetting = this.data.points_setting;
			// pointTotalPrice.plus(this.data.user_points).times(pointSetting)
			pointTotalPrice = new wx.BigNumber(this.data.point.subtract_goodsTotalPrice);
		}

		// 实际支付金额
		let orderPayPrice = orderTotalPrice.minus(pointTotalPrice).minus(couponTotalPrice);
		if (orderPayPrice.comparedTo(0) === -1) {
			orderPayPrice = new wx.BigNumber('0.00');
		}

		this.setData({
			goods_total_price: goodsTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
			order_total_price: orderTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
			order_pay_price: orderPayPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
			point_total_price: pointTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
			coupon_total_price: couponTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
		});
	},

	// 是否开启积分兑换
	pointExchangeChange: function(e) {
		this.data.is_point_exchange = e.detail.value ? 1 : 0;
		this.data.chooseCoupon = null;
		this.groupSetData(() => {
			this.setData({
				is_point_exchange: this.data.is_point_exchange,
				chooseCoupon: null
			});
			this.updateTotalAmount();
		})
	},

	// 切换快递方式
	toggleDeliveryType: function() {
		wx.showActionSheet({
			itemList: ["快递", "线下自提"],
			success: (res) => {
				const delivery = this.data.deliverySetting[res.tapIndex];
				this.setData({
					delivery: delivery
				});
				if (delivery === '20') {
					this.loadShopList();
				}
			}
		})
	},

	// 选择门店
	chooseShopTap: function(e) {
		const index = e.currentTarget.dataset.index;
		const item = this.data.shopList[index];
		this.data.chooseShop = item;
		this.setData({
			chooseShop: item
		});
	},

	// 跳转订单列表
	goOrder: function() {
		wx.redirectTo({
			url: '/pages/user/order/list/list'
		})
	},

	// 立即购买
	payTap: function() {
		if (this.data.goodsId) {
			this.goPay();
		} else {
			this.goPayCart();
		}
	},

	// 直接购买商品
	goPay: function() {
		const chooseCoupon = this.data.chooseCoupon;
		const chooseShop = this.data.chooseShop;
		const address = this.data.address;
		wx.http.post('api/order/buyNow', {
			address_id: address.address_id,
			linkman: address ? address.name : '',
			phone: address ? address.phone : '',
			goods_id: this.data.goodsId,
			goods_sku_id: this.data.goodsSKUId,
			goods_num: this.data.goods_list[0].total_num,
			delivery: this.data.delivery,
			shop_id: chooseShop ? chooseShop.shop_id : 0,
			point: this.data.is_point_exchange ? this.data.point.usage_quantity : 0,
			coupon_id: chooseCoupon ? chooseCoupon.user_coupon_id : 0,
			remark: this.data.remark
		}, {
			showLoading: true
		}).then((res) => {
			const payInfo = res.data.data.payment;

			wx.promise.requestPayment({
				timeStamp: payInfo.timeStamp,
				nonceStr: payInfo.nonceStr,
				package: 'prepay_id=' + payInfo.prepay_id,
				signType: 'MD5',
				paySign: payInfo.paySign,
			}).then(() => {
				this.goOrder();
			}, () => {
				wx.showToast({
					title: '支付失败',
					icon: 'none',
					success: () => {
						this.goOrder();
					}
				});
			});
		});
	},

	// 从购物车直接购买
	goPayCart: function() {
		const chooseCoupon = this.data.chooseCoupon;
		const chooseShop = this.data.chooseShop;
		const address = this.data.address;
		wx.http.post('api/order/cart', {
			address_id: address.address_id,
			cart_ids: this.data.cartIds,
			linkman: address ? address.name : '',
			phone: address ? address.phone : '',
			delivery: this.data.delivery,
			shop_id: chooseShop ? chooseShop.shop_id : 0,
			point: this.data.is_point_exchange ? this.data.point.usage_quantity : 0,
			coupon_id: chooseCoupon ? chooseCoupon.user_coupon_id : 0,
			remark: this.data.remark
		}).then((res) => {
			const payInfo = res.data.data.payment;
			return wx.promise.requestPayment({
				timeStamp: payInfo.timeStamp,
				nonceStr: payInfo.nonceStr,
				package: 'prepay_id=' + payInfo.prepay_id,
				signType: 'MD5',
				paySign: payInfo.paySign,
			}).then(() => {
				this.goOrder();
			}, () => {
				wx.showToast({
					title: '支付失败',
					icon: 'none',
					success: () => {
						this.goOrder();
					}
				});
			});
		});
	},

	// 加载店铺信息
	loadShopList: function() {
		if (this.data.shopList.length) return;
		wx.promise.getLocation().then((res) => {
			return wx.http.get("api/shop/lists", {
				longitude: res.longitude,
				latitude: res.latitude,
			}, {
				showLoading: true
			});
		}, (err) => {
			if (wx.isAuthDeny(err)) {
				wx.openSetting();
			}
			return Promise.reject(err);
		}).then((res) => {
			this.setData({
				shopList: res.data.data.list
			});
		});
	},

	// 更新优惠券
	updateCoupon: function(goodsNum) {
		if (goodsNum === this.data.goodsNum) return;
		console.log('update coupon ...')

		return wx.http.get('api/order/buyNow', {
			goods_id: this.data.goodsId,
			goods_sku_id: this.data.goodsSKUId,
			goods_num: goodsNum,
			delivery: 10,
			shop_id: 0,
			point: 1,
		}).then((res) => {
			const data = res.data.data;
			const couponList = data.coupon_list;

			let chooseCoupon = this.data.chooseCoupon;
			if (couponList.length && chooseCoupon) {
				const index = couponList.findIndex(cp => {
					return chooseCoupon.user_coupon_id === cp.user_coupon_id;
				});
				if (index === -1) chooseCoupon = null;
			} else {
				chooseCoupon = null;
			}

			this.groupSetData(() => {
				if (chooseCoupon === null && this.data.chooseCoupon !== null) {
					this.data.chooseCoupon = null;
					console.log('sszzz');
					this.updateTotalAmount();
				}

				this.setData({
					coupon_list: couponList,
					chooseCoupon: chooseCoupon
				});
			});

			return res.data.data;
		}, (err) => {
			console.warn("api/goods/detail", err)
		});
	},
});
